﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace _00365.Biz
{
    public class Permissions
    {
        public static List<Data.Feature> GetPermissionsFor(Data.UserGroup Group)
        {

            if (Group.Permission == null)
                Group.Permission.Load();

            var features = from i in DBInstance.Models.Permissions
                           where i.Id_UserGroup.Equals(Group.Id)
                           select i.Feature;

            return features.ToList();
        }

        public static Data.Permission Get(Data.Feature Feature, Data.UserGroup Group)
        {
            var perm = from i in DBInstance.Models.Permissions
                       where i.Id_Feature.Equals(Feature.Id) && i.Id_UserGroup.Equals(Group.Id)
                       select i;

            if (perm != null) return perm.FirstOrDefault();
            return null;
        }

        public static Data.Permission Get(Guid Id)
        {
            var perm = from i in DBInstance.Models.Permissions
                       where i.Id.Equals(Id)
                       select i;

            if (perm != null) return perm.FirstOrDefault();
            return null;
        }

        public static void GrantPermissionFor(Data.Feature Feature, Data.UserGroup Group)
        {
            Data.Permission permission = new Data.Permission();
            permission.Id = Guid.NewGuid();
            permission.Id_Feature = Feature.Id;
            permission.Id_UserGroup = Group.Id;
            permission.Active = true;

            DBInstance.Models.AddToPermissions(permission);
            DBInstance.Models.SaveChanges();
        }

        public static void RevokePermissionFor(Guid Id)
        {
            Data.Permission perm = Get(Id);
            if (perm != null)
            {
                DBInstance.Models.Permissions.DeleteObject(perm);
                DBInstance.Models.SaveChanges();
            }
        }

        public static void RevokePermissionFor(Data.Feature Feature, Data.UserGroup Group)
        {
            Data.Permission perm = Get(Feature, Group);
            if (perm != null)
            {
                DBInstance.Models.Permissions.DeleteObject(perm);
                DBInstance.Models.SaveChanges();
            }
        }
    }
}